"""
检查景点数据状态
用于诊断数据是否已更新
"""
from django.core.management.base import BaseCommand
from django.db.models import Count
from django.core.cache import cache
from apps.attractions.models import Attraction


class Command(BaseCommand):
    help = '检查景点数据状态'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('=' * 60))
        self.stdout.write(self.style.SUCCESS('景点数据状态检查'))
        self.stdout.write(self.style.SUCCESS('=' * 60))
        self.stdout.write('')

        # 1. 检查总数量
        total_count = Attraction.objects.count()
        self.stdout.write(f'总景点数量: {total_count}')
        self.stdout.write('')

        # 2. 按类别统计
        self.stdout.write(self.style.WARNING('各类别景点数量:'))
        category_stats = Attraction.objects.values('category').annotate(
            count=Count('id')
        ).order_by('category')
        
        category_names = {
            'cultural': '文化古迹',
            'natural': '自然风光',
            'modern': '现代建筑',
            'food': '美食购物'
        }
        
        for stat in category_stats:
            category = stat['category']
            count = stat['count']
            name = category_names.get(category, category)
            self.stdout.write(f'  {name} ({category}): {count} 个')
        
        self.stdout.write('')

        # 3. 检查重复景点
        self.stdout.write(self.style.WARNING('检查重复景点:'))
        attractions = Attraction.objects.all().order_by('name')
        duplicates_found = []
        
        for i, attr1 in enumerate(attractions):
            similar = []
            for attr2 in attractions[i+1:]:
                # 检查名称相似
                if attr1.name in attr2.name or attr2.name in attr1.name:
                    # 检查位置相近（1公里内）
                    from math import radians, cos, sin, asin, sqrt
                    lat1, lon1 = float(attr1.latitude), float(attr1.longitude)
                    lat2, lon2 = float(attr2.latitude), float(attr2.longitude)
                    lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])
                    dlat = lat2 - lat1
                    dlon = lon2 - lon1
                    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
                    c = 2 * asin(sqrt(a))
                    distance = c * 6371  # 地球半径
                    
                    if distance < 1.0:  # 1公里内
                        similar.append((attr2.name, attr2.id, distance))
            
            if similar:
                duplicates_found.append((attr1.name, attr1.id, similar))
        
        if duplicates_found:
            self.stdout.write(self.style.ERROR(f'发现 {len(duplicates_found)} 组重复景点:'))
            for name, id, similar_list in duplicates_found[:10]:  # 只显示前10组
                self.stdout.write(f'  {name} (ID: {id})')
                for sim_name, sim_id, distance in similar_list:
                    self.stdout.write(f'    - {sim_name} (ID: {sim_id}, 距离: {distance:.2f}km)')
        else:
            self.stdout.write(self.style.SUCCESS('✓ 未发现明显的重复景点'))
        
        self.stdout.write('')

        # 4. 检查图片数据
        self.stdout.write(self.style.WARNING('图片数据统计:'))
        with_amap_images = Attraction.objects.exclude(
            amap_image_urls__isnull=True
        ).exclude(amap_image_urls=[]).count()
        
        with_local_images = Attraction.objects.filter(
            images__isnull=False
        ).distinct().count()
        
        with_primary_image = Attraction.objects.exclude(
            images__isnull=True
        ).distinct().count()
        
        no_images = Attraction.objects.filter(
            images__isnull=True
        ).exclude(
            amap_image_urls__isnull=False
        ).exclude(
            amap_image_urls=[]
        ).count()
        
        self.stdout.write(f'  有高德地图图片: {with_amap_images} 个')
        self.stdout.write(f'  有本地图片: {with_local_images} 个')
        self.stdout.write(f'  有主图: {with_primary_image} 个')
        self.stdout.write(f'  无图片: {no_images} 个')
        self.stdout.write('')

        # 5. 检查缓存
        self.stdout.write(self.style.WARNING('缓存状态:'))
        try:
            # 尝试获取一个缓存键
            test_key = 'attractions_list_'
            cached_data = cache.get(test_key)
            if cached_data:
                self.stdout.write(self.style.WARNING('⚠ 检测到缓存数据'))
                self.stdout.write('  建议执行: python manage.py clear_attractions_cache')
            else:
                self.stdout.write(self.style.SUCCESS('✓ 未检测到缓存数据'))
        except Exception as e:
            self.stdout.write(self.style.WARNING(f'检查缓存时出错: {e}'))
        
        self.stdout.write('')

        # 6. 建议
        self.stdout.write(self.style.SUCCESS('=' * 60))
        self.stdout.write(self.style.SUCCESS('建议操作:'))
        self.stdout.write('=' * 60)
        
        if duplicates_found:
            self.stdout.write('1. 执行去重: python manage.py deduplicate_attractions')
        
        category_counts = {stat['category']: stat['count'] for stat in category_stats}
        if category_counts.get('natural', 0) < 10:
            self.stdout.write('2. 丰富自然风光: python manage.py enrich_attractions_by_category --category natural --max-count 50')
        if category_counts.get('modern', 0) < 10:
            self.stdout.write('3. 丰富现代建筑: python manage.py enrich_attractions_by_category --category modern --max-count 50')
        if category_counts.get('food', 0) < 10:
            self.stdout.write('4. 丰富美食购物: python manage.py enrich_attractions_by_category --category food --max-count 50')
        
        self.stdout.write('5. 清除缓存: python manage.py clear_attractions_cache')
        self.stdout.write('6. 刷新浏览器页面 (Ctrl+F5)')

